package com.vpt;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class CustomAutoCloseableStream {
	
	public static void main(String[] args) {
		try(TeeStream teeStream=new TeeStream(System.out,Paths.get("out.txt"))){
			new PrintStream(teeStream).print("hello,world!");
		} catch (IOException e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
	
	
	public static class TeeStream extends OutputStream{
		private final OutputStream fileStream;
		private final OutputStream outputStream;
		
		public TeeStream(OutputStream outputStream,Path outputFile) throws IOException{
			this.fileStream=new BufferedOutputStream(Files.newOutputStream(outputFile));
			this.outputStream=outputStream;
		}

		@Override
		public void write(int b) throws IOException {
			fileStream.write(b);
			outputStream.write(b);
		}

		@Override
		public void flush() throws IOException {
			outputStream.write("===flush===".getBytes());
			fileStream.flush();
			outputStream.flush();
			
		}
		
		@Override
		public void close() throws IOException{
			try(OutputStream file=fileStream){
				flush();
			}
		}
		
	}
}
